using net_work.Common.Request;
using net_work.Data.Enum.System;
using net_work.IService.IBackgroundTask.IHandler;

namespace net_work.Service.BackgroundTask.Handler;

public class TaskHandlerFactory(IServiceProvider serviceProvider)
{
    public ITaskHandler GetTaskHandler(TaskType taskType)
    {
        // 获取任务类型名称并拼接出处理器的类名
        var handlerTypeName =
            taskType + "TaskHandler";

        // 获取程序集中的所有类型
        var handlerType = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .FirstOrDefault(t => t.Name == handlerTypeName && typeof(ITaskHandler).IsAssignableFrom(t));

        if (handlerType == null)
        {
            throw new ArgumentOutOfRangeException(nameof(taskType), taskType,
                "No handler found for the specified task type.");
        }

        // 通过服务提供者获取该类型的实例
        return (ITaskHandler)serviceProvider.GetRequiredService(handlerType);
    }
}